<template>
  <div v-if="store.isOpen" class="fixed inset-0 bg-app-fg/60 z-40" @click="store.close">
    <div class="fixed top-20 left-1/2 -translate-x-1/2 w-full max-w-xl bg-panel-bg text-panel-fg rounded-lg shadow-2xl z-50" @click.stop>
      <div class="p-2 border-b border-panel-border">
        <input
          ref="searchInput"
          v-model="store.searchQuery"
          type="text"
          placeholder="Search commands..."
          class="w-full px-3 py-2 bg-app-bg border border-panel-border rounded-md focus:outline-none focus:ring-2 focus:ring-accent"
        />
      </div>
      <ul class="max-h-96 overflow-y-auto">
        <li
          v-for="command in store.filteredCommands"
          :key="command.id"
          class="px-4 py-2.5 cursor-pointer hover:bg-app-bg/70"
          @click="store.execute(command.id)"
        >
          {{ command.title }}
        </li>
        <li v-if="store.filteredCommands.length === 0" class="px-4 py-2.5 text-muted-fg">
          No commands found.
        </li>
      </ul>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, nextTick } from 'vue';
import { useCommandPaletteStore } from '../stores/commandPalette';

const store = useCommandPaletteStore();
const searchInput = ref(null);

watch(() => store.isOpen, (isOpen) => {
  if (isOpen) {
    // 当面板打开时，自动聚焦到输入框
    nextTick(() => {
      searchInput.value?.focus();
    });
  }
});
</script>